package com.rich.quartz.quartzjobs;

import com.rich.common.constant.MyGlobalConstant;
import com.rich.common.entity.TbHouse;
import com.rich.common.util.HtmlParseUtil;
import com.rich.quartz.entity.ScheduleJob;
import com.rich.quartz.utils.HttpUtils;
import org.jsoup.nodes.Document;
import org.quartz.*;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

/**
 * @author HanSama
 * @date 2021年08月17日 11:56
 */
//禁止并发执行
@DisallowConcurrentExecution
//持久化JobDataMap 对 trigger无效
@PersistJobDataAfterExecution
public class QuartzJob extends QuartzJobBean {



    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {

        try {
            System.out.println(context.getScheduler().getSchedulerInstanceId());

            System.out.println("taskname:"+context.getJobDetail().getKey().getName());


            //取出页数
            JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
            int page = jobDataMap.getInt("page");

            System.out.println(page++);

            jobDataMap.put("page",page);

//        String type = "zufang";
            //设置爬取房源类型
            String type = MyGlobalConstant.HouseConstant.ER_SHOU_FANG;

            //获取页面信息 //双引号里面填写网址
            Document document= HtmlParseUtil.getDocument("https://bj.5i5j.com/"+type+"/n"+page);

            //获取文档对象
            ArrayList<TbHouse> tbHouses = HtmlParseUtil.parseZuFangHtml(document);

            /**
             * 添加房源信息到数据库
             */


            System.out.println("执行时间："+new Date());

        } catch (Exception e) {
            e.printStackTrace();
            ScheduleJob scheduleJob = (ScheduleJob)context.getMergedJobDataMap().get("scheduleJob");
            try {
                //暂停任务
                HttpUtils.sendGet("http://localhost:8008/quartz/pauseQuartz?jobName="+scheduleJob.getJobName()+"&jobGroup="+scheduleJob.getJobGroup());
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }
    }
}
